package com.oocl.crm.parser.impl;

import java.util.Arrays;

import com.oocl.crm.customer.Customer;
import com.oocl.crm.db.MyLinkedList;
import com.oocl.crm.parser.CmdParser;
import com.oocl.crm.repository.CustomerDataProcess;
import com.oocl.crm.repository.impl.CustomerDataProcessImpl;
import com.oocl.crm.util.Add;
import com.oocl.crm.util.FormatPrinter;

public class CmdParserImpl implements CmdParser {
	
	private CustomerDataProcess<Customer> cdp;
	private MyLinkedList<Customer> mll;
	public CmdParserImpl(MyLinkedList<Customer> mll){
		this.mll=mll;
	}
	
	@Override
	public void processAdd(String cmd) {
		cdp=new CustomerDataProcessImpl(mll);
		Customer c=new Customer("null","null","null","null","null","null");
		
		String[] str1=cmd.split(" ");
		String[] str2=str1[1].split(",");
		String[] str3;
		
		for (int i = 0; i < str2.length; i++) {
			str3=str2[i].split(":");
			Add.addOrUpdateInformation(c, str3);
		}
		if(c.getName()=="null"){
			FormatPrinter.printNeedName();
			return;
		}
		String id;
		int l=mll.getSize();
		if(l<9){
			l++;
			id="0"+String.valueOf(l);
		}
		else{
			l++;
			id=String.valueOf(l);
		}
		c.setId(id);
		cdp.addCustomer(c);	
	}

	@Override
	public void processUpdate(String cmd) {
		cdp=new CustomerDataProcessImpl(mll);
		String[] str1=cmd.split(" ");
		String id = str1[1];
		String[] str2=str1[2].split(",");
		String[] str3;
		Customer clone;
		clone=cdp.cloneCustomer(id);
		if(clone==null){
			FormatPrinter.printNoSuchCustomer(null);
			return;
		}
		for (int i = 0; i < str2.length; i++) {
			str3=str2[i].split(":");
			Add.addOrUpdateInformation(clone, str3);
		}
		cdp.updateCustomer(id, clone);
	}

	@Override
	public void processDelete(String cmd) {
		cdp=new CustomerDataProcessImpl(mll);
		//
		String[] str1=cmd.split(" ");
		String id = str1[1];
		cdp.deleteCustomer(id);
	}

	@Override
	public Customer[] processSort(String cmd) {
		cdp=new CustomerDataProcessImpl(mll);
		Customer[] view;
		String[] str1=cmd.split(" ");
		String p = str1[1];
		view=cdp.sort(p);
		return view;
	}

	@Override
	public Customer[] find(String cmd) {
		cdp=new CustomerDataProcessImpl(mll);
		Customer[] view;
		String str1[]=cmd.split(" ");
		if(str1.length==1)view=cdp.allCustomers();
		else{
			String str2[]=str1[1].split(",");
			view = cdp.find(str2);
		}
		return view;
	}
	
	@Override
	public void processHelp(String cmd){
		cdp=new CustomerDataProcessImpl(mll);
		Customer[] view;
		String str1[]=cmd.split(" ");
		if(str1.length==1)view=cdp.allCustomers();
	}
}
